<?php

namespace Biz\service\GoodsTestActivity;

use Biz\cache\brand\FineGoodsTest;
use Biz\model\brandActivity\BrandActivityBasic;
use Biz\model\GoodsTestActivity\FineGoodsContentModel;
use Biz\model\GoodsTestActivity\FineGoodsJoinModel;
use Biz\model\GoodsTestActivity\FineGoodsJoinRecordModel;
use Biz\model\GoodsTestActivity\FineGoodsModel;
use Biz\model\GoodsTestActivity\FineGoodsMsgModel;
use Biz\model\GoodsTestActivity\FineGoodsPeopleReplaceModel;
use Biz\model\GoodsTestActivity\FineGoodsWishMsgModel;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\pockets\constInterface\SourceRightsInterface;
use Biz\service\brand\BrandActivity;
use Biz\service\BrandRights\BrandEquityVerificationService;
use Biz\service\BrandRights\BrandRightsAllService;
use Biz\service\NewProduct\NewProductWinnerListService;
use Biz\service\wiki\Wiki;
use Biz\tools\helper\Common;
use Doraemon\model\Blank;
use Doraemon\model\CommunityMcn\GoodsRecommender as mGoodsRecommender;
use Doraemon\model\Photos;
use Doraemon\pockets\constInterface\FormatScene;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\service\Format\Blank\HandleBlank;
use Doraemon\service\Format\Note\HandleNote;
use Doraemon\service\User as mUser;
use Doraemon\tools\BlockType;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;
use Doraemon\model\Phone as PhoneModel;
use hhz\constant\basic\UserExtendPhoneScene;
use Exception;


class FineGoodsService
{
    /**
     * @param array $field
     * @param array $where
     * @param $pageSize
     * @return array|bool
     */

    public static function getList(array $field, array $where, $pageSize): array
    {
        $result = FineGoodsModel::selectList($where, $field);
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $total = FineGoodsModel::selectCount($where);
        $res = [];
        if ($result) {
            $ids = array_column($result, 'id');
            $noShippedCountMap = self::getCountNoShippedByIds($ids);

            foreach ($result as &$row) {
                if ($row['schedule_start_time'] > 0 && $row['schedule_end_time'] > 0) {
                    $row['schedule_time'] = date('Y.m.d', $row['schedule_start_time']) . ' - ' . date('Y.m.d',
                            $row['schedule_end_time']);
                } else {
                    $row['schedule_time'] = '暂无排期';
                }
                if ($row['type'] == FineGoodsModel::TYPE_LIGHT_TEST) {
                    $row['activity_title'] = '轻测 | ' . $row['activity_title'];
                } else {
                    $row['activity_title'] = '开箱 | ' . $row['activity_title'];
                }
                $noShippedCount = $noShippedCountMap[$row['id']] ?? 0; // 未发货数量
                $row['no_shipped_count'] = $noShippedCount;
                $row['is_all_shipped'] = ($noShippedCount == $row['goods_num']) ? 1 : 0; //是否全部发货
            }
            $res['total'] = $total;
            $res['is_over'] = $pageSize < $total ? 0 : 1;
            $res['list'] = $result;
        }

        return $res;
    }

    /**
     * 根据活动id集合 获取每个活动对应的首选用户未发货人数
     * @param array $ids
     * @return array
     */
    public static function getCountNoShippedByIds(array $ids): array
    {
        if ($ids) {
            $where = [
                'fine_goods_id' => $ids,
                'join_status' => FineGoodsJoinModel::JOIN_STATUS_PREFER,
                'logistics_status' => FineGoodsJoinModel::LOGISTICS_STATUS_NO_SHIPPED,
                "GROUP" => "fine_goods_id",
            ];

            return NewProductWinnerListService::handleCount(FineGoodsJoinModel::getCountMaps($where), 'fine_goods_id');
        } else {
            return [];
        }

    }

    /**
     * 获取用户已获选的文章数量
     *  示例 [1,2,3]
     * @param array $uidArr
     * @return array
     */
    public static function getCountContentsByUidArr(array $uidArr): array
    {
        if ($uidArr) {
            $where = [
                'uid' => $uidArr,
                'is_delete' => FineGoodsContentModel::IS_DELETE_FALSE,
                "GROUP" => "uid",
            ];

            return NewProductWinnerListService::handleCount(FineGoodsContentModel::getCountMaps($where), 'uid');
        } else {
            return [];
        }
    }

    /**
     * 保存活动/[创建、编辑]
     * @param array $data
     * @param int $id
     * @return bool
     * @throws \Exception
     */
    public static function saveData(array $data, int $id = 0): bool
    {
        //过滤空的亮点文案
        if (isset($data['advantage_text']) && !empty($data['advantage_text'])) {
            $data['advantage_text'] = json_encode(array_filter(json_decode($data['advantage_text'], true)),
                JSON_UNESCAPED_UNICODE);
        }
        //过滤空的特殊说明文案
        if (isset($data['desc_text']) && !empty($data['desc_text'])) {
            $data['desc_text'] = json_encode(array_filter(json_decode($data['desc_text'], true)),
                JSON_UNESCAPED_UNICODE);
        }
        $brandId = $data['brand_id'];


        //获取套餐剩余次数
//        $packageCountMap = NewProductWinnerListService::handleData(PackageService::getPackageList($brandId),
//            'package',
//            'remaining_times');


        $packageCountMap = BrandRightsAllService::getGoodTestPackNum($brandId);

        if ($id) {
            return self::updateActivity($data, $packageCountMap, $id);
        } else {
            return self::addActivity($data, $packageCountMap);
        }
    }

    /**
     * 编辑活动
     * @param $data
     * @param $packageCountMap
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public static function updateActivity($data, $packageCountMap, $id): bool
    {
        $info = FineGoodsModel::getById($id, false);//查询原始数据，非format数据

        $type = $data['type'];
        $packageCombinationArrOld = json_decode($info['package_combination'], true) ?? [];
        $packageCombinationArrNew = json_decode($data['package_combination'], true) ?? [];
        $packageCombinationArrNewPackage = array_column($packageCombinationArrNew, 'package');
        $packageCombinationArrOldPackage = array_column($packageCombinationArrOld, 'package');
        asort($packageCombinationArrNewPackage);
        asort($packageCombinationArrOldPackage);
        if ($info['activity_state'] == FineGoodsModel::STATE_DEL) {
            throw new \Exception('当前状态无权操作');
        }
        //检查当前状态是否可进行编辑操作
        if ($data['operate_type'] == FineGoodsModel::OPERATE_TYPE_USER) { //品牌服务端只有草稿以及审核不通过才可编辑
            if (!in_array($info['activity_state'],
                [FineGoodsModel::STATE_DEFAULT, FineGoodsModel::STATE_NOT_PASS])) {
                throw new Exception('此状态下不可再次编辑，只有草稿和审核不通过才可编辑');
            }
            // 测评活动无套餐 不需校验 这里只校验type<3的
            if ($packageCombinationArrNewPackage != $packageCombinationArrOldPackage && ($type < FineGoodsModel::TYPE_EVALUATION)) {
                throw new \Exception('您无权更换套餐');
            }
            //检查品牌对应的套餐次数 测评类型没有套餐 这里只校验 type<3 活动类型的
            if ($data['activity_state'] != FineGoodsModel::STATE_DEFAULT && ($type < FineGoodsModel::TYPE_EVALUATION)) {
                foreach ($packageCombinationArrNew as $item) {
                    if ($packageCountMap[$item['package']] <= 0) {
                        throw new Exception('您的好物轻测机会已用完，请联系平台运营购买新的活动次数');
                    }
                }
            }

            //权益数量操作 测评类型不消耗权益 这里只校验 type<3 活动类型的
            if ($type < FineGoodsModel::TYPE_EVALUATION) {
                $sourceId = BrandActivityBasic::getSourceId(BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $id);
                //如果之前状态为草稿或则审核不通过 且 当前为非草稿，则消耗活动次数
                if (in_array($info['activity_state'], [FineGoodsModel::STATE_DEFAULT, FineGoodsModel::STATE_NOT_PASS])
                    && $data['activity_state'] == FineGoodsModel::STATE_WAIT) {
                    foreach ($packageCombinationArrNew as $item) {

                        BrandEquityVerificationService::subNum(
                            $data['brand_id'],
                            $sourceId,
                            SourceRightsInterface::GOODS_TEST[$item['package']]
                        );
                    }
                }
            }

        } else {
            //由于测评类型的活动 没有套餐且不需要消耗权益 所以不需验证
            if ($type < FineGoodsModel::TYPE_EVALUATION) {
                if ($packageCombinationArrNewPackage != $packageCombinationArrOldPackage) {
                    //检查品牌对应的套餐次数
                    foreach ($packageCombinationArrNew as $item) {
                        if ($packageCountMap[$item['package']] <= 0) {
                            throw new Exception('您的好物轻测机会已用完，请联系平台运营购买新的活动次数');
                        }
                    }
                    if (in_array($info['activity_state'], [FineGoodsModel::STATE_WAIT, FineGoodsModel::STATE_PASS])) {
                        //如果之前状态为审核通过，或则待审核，返回之前套餐的次数
                        foreach ($packageCombinationArrOld as $item) {

                            BrandEquityVerificationService::activityRightsRefund($data['brand_id'], $id,
                                BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $data['operate_uid'],
                                ['package' => $item['package']]);
                        }
                    }
                    $sourceId = BrandActivityBasic::getSourceId(BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $id);
                    //消耗权益次数(新套餐的次数)
                    foreach ($packageCombinationArrNew as $item) {

                        //权益数量操作
                        BrandEquityVerificationService::subNum(
                            $data['brand_id'],
                            $sourceId,
                            SourceRightsInterface::GOODS_TEST[$item['package']]
                        );
                    }
                }
            }
        }
        $data['edittime'] = date('Y-m-d H:i:s', time());
        FineGoodsModel::update($data, ['id' => $id]);
        return true;
    }

    /**
     * @param int $id
     * @param array $field
     * @return array
     */
    public static function getById(int $id, array $field = []): array
    {
        if (!$field) {
            $field = '*';
        }
        $where['id'] = $id;
        $where['activity_state[!]'] = FineGoodsModel::STATE_DEL;

        return FineGoodsModel::first($where, $field) ?? [];
    }

    /**
     * 添加活动
     * @param $data
     * @param $packageCountMap
     * @return bool
     * @throws \Exception
     */
    public static function addActivity($data, $packageCountMap): bool
    {
        //检查品牌对应的套餐次数
        $packageCombinationArr = json_decode($data['package_combination'], true);

        foreach ($packageCombinationArr as $item) {
            if ($packageCountMap[$item['package']] <= 0) {
                throw new Exception('当前使用套餐次数不足');
            }
        }

        $id = FineGoodsModel::insertData($data);
        if (!$id) {
            throw new \Exception('添加活动失败');
        }
        //权益数量操作
        $sourceId = BrandActivityBasic::getSourceId(BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $id);
        if ($data['activity_state'] != FineGoodsModel::STATE_DEFAULT) {//新增活动不为草稿，消耗次数
            foreach ($packageCombinationArr as $item) {

                BrandEquityVerificationService::subNum(
                    $data['brand_id'],
                    $sourceId,
                    SourceRightsInterface::GOODS_TEST[$item['package']]
                );
            }
        }

        return true;
    }

    /**
     * 获取活动中的列表
     * @param string $field
     * @return array|bool
     */
    public static function getActIngList($field = "*")
    {
        $where['activity_state'] = FineGoodsModel::STATE_PASS;
        $where['schedule_start_time[<=]'] = time();
        $where['schedule_end_time[>]'] = time();
        $where['ORDER'] = ['schedule_start_time' => 'DESC', 'id' => 'DESC'];

        return FineGoodsModel::all($where, $field);
    }

    /**
     * 获取单条活动详情
     * @param $id
     * @param string $field
     * @return array|mixed|null
     */
    public static function getActIngInfo($id, $field = '*')
    {
        $where['activity_state'] = FineGoodsModel::STATE_PASS;
        $where['schedule_start_time[<=]'] = time();
        $where['schedule_end_time[>]'] = time();
        $where['id'] = $id;

        return FineGoodsModel::first($where, $field);

    }

    /**
     * 体验中的活动列表
     * @param string $filed
     * @return array|bool
     */
    public static function getActLearnList($filed = "*")
    {
        $list = [];
        $where['activity_state'] = FineGoodsModel::STATE_PASS;
        $where['schedule_end_time[<]'] = time();
        $where['schedule_end_time[!]'] = 0;
        $where['report_num'] = 0;
        $where['ORDER'] = ['schedule_end_time' => 'DESC'];

        //最新一期的评测
        $lastWhere = $where;
        $lastWhere['type'] = FineGoodsModel::TYPE_EVALUATION;
        $lastEvluationInfo = FineGoodsModel::first($lastWhere);
        if ($lastEvluationInfo) {
            $where['id[!]'] = $lastEvluationInfo['id'];
            $list[] = $lastEvluationInfo;
        }
        $all = FineGoodsModel::all($where, $filed);
        $list = array_merge($list, $all);
        return $list;
    }

    /**
     * 获取参与活动记录
     * @param $where
     * @param string $filed
     * @return array|bool
     */
    public static function getJoinInfoById($where, $filed = "*")
    {
        return FineGoodsJoinModel::all($where, $filed);
    }

    /**
     * 获取已完成活动列表
     * @param $category_tag
     * @param $start
     * @param $per_page
     * @param string $filed
     * @return array
     */
    public static function getReportList($category_tag, $start, $per_page, $filed = '*')
    {
        $where['activity_state'] = FineGoodsModel::STATE_PASS;
        $where['schedule_end_time[<]'] = time();
        $where['schedule_end_time[!]'] = 0;
        $where['report_num[>]'] = 0;
        if ($category_tag) {
            $where['category_tag_id'] = $category_tag;
        }
        $where["LIMIT"] = [$start, $per_page];
        $where['ORDER'] = ['schedule_end_time' => "DESC"];

        $list = [];

        //最新一期的评测
        $lastWhere = $where;
        unset($lastWhere['LIMIT']);
        unset($lastWhere['category_tag_id']);
        $lastWhere['type'] = FineGoodsModel::TYPE_EVALUATION;
        $lastEvluationInfo = FineGoodsModel::first($lastWhere);
        if ($lastEvluationInfo) {
            if ($category_tag == 0 || $lastEvluationInfo['category_tag_id'] == $category_tag) {
                $where['id[!]'] = $lastEvluationInfo['id'];
                $list[] = $lastEvluationInfo;
            }
        }

        $total = FineGoodsModel::count($where);
        $all = FineGoodsModel::all($where, $filed);
        $list = array_merge($list, $all);
        $data['total'] = $total;
        $data['list'] = $list;

        return $data;
    }

    /**
     * 获取消息列表
     * @param $where
     * @return array
     */
//    public static function getMsgListByWhere($where)
//    {
//
//        $filed = ["uid", "content", 'msg_type'];
//        $msg_info = FineGoodsMsgModel::all($where, $filed);
//        $msg_list = [];
//        if ($msg_info) {
//            $user_ids = array_column($msg_info, 'uid');
//            $user_info = mUser::getBatchBasicUserInfo($user_ids);
//            $user_info = array_column($user_info, null, 'uid');
//            foreach ($msg_info as $k => $v) {
//                $nick = $user_info[$v['uid']]['nick'] ?? '';
//                $msg_list[$k]['content'] = $nick . $v['content'] ?? '';
//                $msg_list[$k]['avatar'] = $user_info[$v['uid']]['avatar'] ?? '';
//                $msg_list[$k]['uid'] = $v['uid'];
//            }
//        }
//
//        return $msg_list;
//    }

    /**
     * 获取pv
     * @param $list
     * @param bool $get_avatar
     * @return array []
     */
    public static function getFineGoodsPv($list, bool $get_avatar = true): array
    {
        $ids = array_column($list, 'id');

        $cache_data = FineGoodsTest::hGetItems($ids);

        foreach ($list as &$item) {

            $item['interested_num'] = $cache_data[$item['id']] ?? 0;
            if ($get_avatar) {
                $item['avatar_list'] = Common::getRandAvatars();
            }
        }

        return $list;
    }

    /**
     * 获取消息列表(如果根据wish_id来获取内容)
     * @param $where
     * @param string $from
     * @return array
     */
    public static function getMsgListByWhere($where, string $from = '')
    {
        $msg_list = [];
        $filed = ["uid", "wish_id", 'msg_type', 'id', 'fine_goods_id'];
        $msg_info = FineGoodsMsgModel::all($where, $filed);
        if (!$msg_info) {
            return $msg_list;
        }
        $fine_goods_ids = array_column($msg_info, 'fine_goods_id');
        $fine_goods = FineGoodsModel::all(['id' => array_filter($fine_goods_ids)], ['id', 'brand_name', 'activity_title', 'type']);
        $fine_goods = array_column($fine_goods, null, 'id');
        foreach ($msg_info as &$info) {
            $info['brand_name'] = $fine_goods[$info['fine_goods_id']]['brand_name'] ?? '';
            $info['activity_title'] = $fine_goods[$info['fine_goods_id']]['activity_title'] ?? '';
        }

        $user_ids = array_column($msg_info, 'uid');
        $user_info = mUser::getBatchBasicUserInfo($user_ids);
        $user_info = array_column($user_info, null, 'uid');
        $wish_msg_data = FineGoodsWishMsgModel::all([], ['id', 'content', 'emoji_url']);
        $wish_msg_data = array_column($wish_msg_data, null, 'id');
        foreach ($msg_info as $k => $v) {
            if ($v['wish_id'] && (int)$v['msg_type'] === FineGoodsMsgModel::MSG_WISH) {
                $wish_msg_info = self::getContent($wish_msg_data, $v['brand_name'], $v['wish_id']);
                $msg_list[$k]['emoji_url'] = $wish_msg_info['emoji_url'];
                $content = $wish_msg_info['content'];
            }
            if ((int)$v['msg_type'] === FineGoodsMsgModel::MSG_APPLY) {
                $content = "参与了" . $v['activity_title'] . "的免费测评";
            }
            if ((int)$v['msg_type'] === FineGoodsMsgModel::MSG_SUCCESS) {
                $content = "获得了" . $v['activity_title'] . "的测评名额";
            }
            $msg_list[$k]['nick'] = $user_info[$v['uid']]['nick'];
            $msg_list[$k]['content'] = $content ?? '';
            $msg_list[$k]['avatar'] = $user_info[$v['uid']]['avatar'] ?? '';
            $msg_list[$k]['uid'] = $v['uid'];
            $msg_list[$k]['id'] = $v['id'];
            $msg_list[$k]['msg_type'] = $v['msg_type'];
        }

        return $msg_list;
    }

    /**
     * 批量获取许愿内容
     * @param $wish_msg_data
     * @param $brand_name
     * @param $wish_id
     * @return string[]
     */
    private static function getContent($wish_msg_data, $brand_name, $wish_id)
    {
        $content = str_replace("{品牌名}", $brand_name,
            $wish_msg_data[$wish_id]['content']) ?: $wish_msg_data[$wish_id]['content'];
        $emoji_url = $wish_msg_data[$wish_id]['emoji_url'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
            $wish_msg_data[$wish_id]['emoji_url'],
            ImgUrl::IMAGE_SIZE_ORI_NPHONE) : '';

        return ['content' => $content, 'emoji_url' => $emoji_url];
    }

    /**
     * @param $fine_goods_id
     * @param $from_id
     * @param $from_uid
     * @param $to_id
     * @param $to_uid
     * @param $operate_type
     * @param $operate_id
     * @return bool
     * @throws \Exception
     */
    public static function peopleReplace(
        $fine_goods_id,
        $from_id,
        $from_uid,
        $to_id,
        $to_uid,
        $operate_type,
        $operate_id
    ): bool
    {
        //获取基本信息
        $info = self::getById($fine_goods_id,
            ['goods_num', 'brand_id', 'activity_state', 'schedule_start_time', 'schedule_end_time', 'report_num']);
        if ($info) {
            //检查当前状态下是否可以替换首选人 (品牌后台有此限制，运营后台无此限制)
            if ($info['activity_state'] != FineGoodsModel::STATE_VERIFY && $operate_type == FineGoodsPeopleReplaceModel::OPERATE_TYPE_BRAND) {
                throw new Exception('尚未达到可操作时间,只有名单审核中状态才可操作');
            }
            $goods_num = $info['goods_num'];
            $brand_id = $info['brand_id'];
            //检查发货状态 如果已发货 则不能替换用户
            $logisticsStatus = FineGoodsJoinModel::get('logistics_status', ['id' => $from_id]);
            if ($logisticsStatus == FineGoodsJoinModel::LOGISTICS_STATUS_SHIPPED) {
                throw new Exception('该用户已发货，不可替换');
            }
            //检查该活动替换用户次数
            if ($operate_type == FineGoodsPeopleReplaceModel::OPERATE_TYPE_BRAND) {
                self::checkReplaceLaveNum($fine_goods_id, $goods_num);
            }
            $edittime = date('Y-m-d H:i:s', time());
            //替换用户
            $res = FineGoodsJoinModel::update([
                'join_status' => FineGoodsJoinModel::JOIN_STATUS_DEL,
                'edittime' => $edittime,
            ],
                ['id' => $from_id]);
            if ($res) {
                //查看该备选用户之前是否是被首选过的用户
                $isExist = FineGoodsJoinModel::get(['id', 'record_id'], ['record_id' => $to_id]);
                if ($isExist) {
                    FineGoodsJoinModel::update([
                        'join_status' => FineGoodsJoinModel::JOIN_STATUS_PREFER,
                    ], ['id' => $isExist['id']]);
                } else {
                    FineGoodsJoinModel::insert([
                        'fine_goods_id' => $fine_goods_id,
                        'record_id' => $to_id,
                        'uid' => $to_uid,
                        'join_status' => FineGoodsJoinModel::JOIN_STATUS_PREFER,
                    ]);
                }
                //记录
                FineGoodsPeopleReplaceModel::insert([
                    'fine_goods_id' => $fine_goods_id,
                    'brand_id' => $brand_id,
                    'from_uid' => $from_uid,
                    'to_uid' => $to_uid,
                    'operate_type' => $operate_type,
                    'operate_id' => $operate_id,
                ]);

                return true;
            } else {
                throw new Exception('替换失败');
            }

        } else {
            throw new Exception('活动不存在');
        }
    }

    /**
     * 检查该活动替换用户次数
     * @param $fine_goods_id
     * @param $goods_num
     * @param int $flag
     * @return int|void
     * @throws \Exception
     */
    public static function checkReplaceLaveNum($fine_goods_id, $goods_num, int $flag = 0)
    {
        $num = FineGoodsPeopleReplaceModel::selectCount([
            'fine_goods_id' => $fine_goods_id,
            'operate_type' => FineGoodsPeopleReplaceModel::OPERATE_TYPE_BRAND,
        ]);

        $goods_num = (int)$goods_num;
        $num = (int)$num;
        //检查次数
        switch ($goods_num) {
            case 1://当 1-3 人时：可替换人数有 1 次机会；
            case 2:
            case 3:
                $frequency = 1;
                break;
            case 4:  //当 4 人时：可替换人数有 2 次机会；
            case 5:
                $frequency = 2;
                break;
            case 6://当 6-10 人时：可替换人数有 3 次机会；
            case 7:
            case 8:
            case 9:
            case 10:
                $frequency = 3;
                break;
            case 11:  //当 11-15 人时：可替换人数有 4 次机会；
            case 12:
            case 13:
            case 14:
            case 15:
                $frequency = 4;
                break;
            default:
                $frequency = 0;
        }

        if ($flag == 1) { //返回剩余可替换次数
            return $frequency - $num;
        }
        if ($num >= $frequency) {
            throw new Exception('您替换名额次数已用完');
        }
    }

    /**
     * @param $id
     * @return array
     * @throws \Exception
     */
    public static function peopleReplaceDetail($id): array
    {
        $info = FineGoodsJoinModel::get(['record_id', 'fine_goods_id', 'uid'],
            ['id' => $id, 'join_status' => FineGoodsJoinModel::JOIN_STATUS_PREFER]);
        if (!$info) {
            throw new Exception('数据不存在');
        }
        //查询当前首选用户的粉丝区间等级
        $recordInfo = FineGoodsJoinRecordModel::get(['fans_num_grade', 'fans_num'], ['id' => $info['record_id']]);

        //当前首选用户数据
        $userInfo = mUser::getUser($info['uid']);
        list($scoreMap, $tag) = BigDataService::getScoreMap([$info['uid']]);
        $result = [];
        $result['id'] = $info['fine_goods_id'];
        $result['prefer'] = [
            'from_id' => $id,
            'from_uid' => $info['uid'],
            'fans_num' => $recordInfo['fans_num'],
            'user_nick' => $userInfo['nick'],
            'user_avatar' => $userInfo['avatar'],
            'tag_list' => $tag[$info['uid']]['tag'] ?? '',
            'user_score' => $scoreMap[$info['uid']] ?? [],
        ];
        //查询该活动下的备选名单
        $notPreferList = self::getNotPrefer($info['fine_goods_id'], ['record_id']);
        if ($notPreferList) {
            //查找符合粉丝区间等级并且是备选用户数据集合
            $where['id'] = array_column($notPreferList, 'record_id');
            $where['fans_num_grade'] = $recordInfo['fans_num_grade'];
            $field = ['id', 'fans_num', 'uid', 'fine_goods_id'];
            $data = FineGoodsJoinRecordModel::select($field, $where);
            //随机选出一个
            if ($data) {
                $randKey = array_rand($data);
                $data = $data[$randKey];
                //当前备选用户数据
                $userInfo = mUser::getUser($data['uid']);
                list($scoreMap, $tag) = BigDataService::getScoreMap([$data['uid']]);
                $result['not_prefer'] = [
                    'to_id' => $data['id'],
                    'to_uid' => $data['uid'],
                    'fans_num' => $data['fans_num'],
                    'user_nick' => $userInfo['nick'],
                    'user_avatar' => $userInfo['avatar'],
                    'tag_list' => $tag[$data['uid']]['tag'] ?? '',
                    'user_score' => $scoreMap[$data['uid']] ?? [],
                ];
            }
        }

        return $result;
    }

    /**
     * 获取备选名单
     * @param int $fineGoodsId
     * @param array $field
     * @return array
     */
    public static function getNotPrefer(int $fineGoodsId, array $field = []): array
    {
        if (!$field) {
            $field = '*';
        }
        $where['fine_goods_id'] = $fineGoodsId;
        $where['join_status'] = FineGoodsJoinModel::JOIN_STATUS_NOT_PREFER;

        return FineGoodsJoinModel::select($field, $where);
    }

    /**
     * @param int $id
     * @param int $brandId
     * @return array
     * @throws \Exception
     */
    public static function getInfo(int $id, int $brandId): array
    {
        //获取套餐列表数据
        $packageList = PackageService::getPackageList($brandId);
        if (!$id) {
            return ['package_list' => $packageList];
        }
        $info = self::getById($id, [
            'id',
            'brand_id',
            'activity_title',
            'basic_id',
            'basic_title',
            'goods_num',
            'goods_worth',
            'schedule_start_time',
            'schedule_end_time',
            'package',
            'cover_img',
            'advantage_img',
            'advantage_text',
            'activity_state',
            'report_num',
            'package_combination',
            'type',
        ]);
        //品牌归属校验
        if ($info['brand_id'] != $brandId) {
            throw new Exception('非法请求');
        }
        if ($info['schedule_start_time'] > 0 && $info['schedule_end_time'] > 0) {
            $info['schedule_start_time'] = date('Y-m-d', $info['schedule_start_time']);
            $info['schedule_end_time'] = date('Y-m-d', $info['schedule_end_time']);
            $info['schedule_time'] = $info['schedule_start_time'] . ' | ' . $info['schedule_end_time'];

        } else {
            $info['schedule_start_time'] = '';
            $info['schedule_end_time'] = '';
            $info['schedule_time'] = '暂无排期';
        }
        //图片返回格式处理
        $info['cover_img_map'] = [
            'ori_pic_id' => $info['cover_img'],
            'ori_without_watermark' => $info['cover_img_url'],
        ];

        if ($info['advantage_img_id']) {
            $i = 0;
            foreach ($info['advantage_img_id'] as $val) {
                $res['ori_pic_id'] = $val;
                $res['ori_without_watermark'] = $info['advantage_img'][$i];
                $i++;
                $info['advantage_img_map'][] = $res;
            }
        }
        $info['package_list'] = $packageList;
        $info['description'] = self::peopleReplaceNewInfo($id);

        //获取测评报告
        $reportList = FineGoodsContentModel::select('*',
            ['fine_goods_id' => $id, 'is_delete[!]' => FineGoodsContentModel::IS_DELETE_TRUE]);
        $info['content'] = self::formatNoteList($reportList);
        //获取首选名单（只有所有名单全部选出时才返回数据）
        $joined = self::getJoined($id);
        $countJoined = count($joined);

        if ($countJoined >= $info['goods_num'] && $countJoined > 0) {
            $info['user_list'] = self::formatJoined($joined);

        }

        return $info;

    }

    /**
     * @param $fineGoodsId
     * @return array
     */
    public static function peopleReplaceNewInfo($fineGoodsId): array
    {
        $activityInfo = FineGoodsModel::first(['id' => $fineGoodsId], ['goods_num', 'schedule_end_time']);
        $scheduleEndTime = $activityInfo['schedule_end_time'];

        if ($scheduleEndTime > 0) {
            $goodsNum = $activityInfo['goods_num'];
            $schedule = date('Y-m-d', $activityInfo['schedule_end_time'] + FineGoodsModel::VERIFY_USER_TIME);
            $num = self::checkReplaceLaveNum($fineGoodsId, $goodsNum, 1) ?? 0;//获取剩余可替换次数
            $data ['footer'] = "本次测评人数为 $goodsNum 人，" . $schedule . '日前您有替换' . $num . '人的机会，' . '替换后无法撤销';
        } else {
            $data ['footer'] = '';
        }

        $field = ['addtime', 'operate_type', 'operate_id'];
        $where ['fine_goods_id'] = $fineGoodsId;
        $where ['ORDER'] = ['id' => 'DESC'];
        $info = FineGoodsPeopleReplaceModel::get($field, $where);
        $addtime = $info['addtime'];
        $operateType = $info['operate_type'];
        $operateName = FineGoodsPeopleReplaceModel::OPERATE_TYPE_MAP[$operateType];
        if ($info) {
            $data ['header'] = "最后更新时间: $addtime ，" . '操作方:' . $operateName;
        } else {
            $data ['header'] = '暂无操作记录';

        }

        return $data;

    }

    /**
     * 格式化处理评测报告内容数据
     * @param $list
     * @return array
     */
    public static function formatNoteList($list): array
    {
        $result = [];
        if ($list) {
            $noteIds = array_unique(array_column($list, 'obj_id'));
            $basicIds = array_unique(array_column($list, 'basic_id'));
            $noteIdArr = [];
            $blankIdArr = [];
            foreach ($noteIds as $obj_id) {
                $obj_type = IdParse::getType($obj_id);
                if ((int)$obj_type === BlockType::TYPE_PHOTO) {
                    $noteIdArr[] = $obj_id;
                }
                if ((int)$obj_type === BlockType::TYPE_BLANK) {
                    $blankIdArr[] = $obj_id;
                }
            }
            $noteData = HandleNote::handleNote($noteIdArr, FormatScene::BASE_INFO, 0) ?: [];
            $blankData = HandleBlank::handleBlank($blankIdArr, FormatScene::BASE_INFO, 0) ?: [];
            $objWikiInfo = self::getRelatedWikiByNoteIds($noteIds);
            $wikiDataMap = mWiki::getDefaultWikiInfoByBasicIds($basicIds);
            if ($wikiDataMap) {
                $wikiDataMap = NewProductWinnerListService::handleData($wikiDataMap, 'basic_id', 'id');
            }
            $result = [];
            foreach ($list as $value) {

                $res['obj_id'] = $value['obj_id'] ?? '';// note id

                $res['points'] = $value['points'] ?? 0; //分值
                $res['id'] = $value['id'] ?? 0; //主键id
                $res['link'] = self::creatLinkUrl($value['obj_id']); //扫码url
                $objWikiInfoArr = $objWikiInfo[$value['obj_id']] ?? [];
                $res['obj_wiki_info'] = $objWikiInfoArr; //商品关联wiki
                $res['obj_wiki_info_name_map'] = implode(',',
                        array_column($objWikiInfoArr, 'title')) ?? ''; //商品关联wiki title 集合
                $objWikiInfoWikiIdArr = array_column($objWikiInfoArr, 'id');
                $res['obj_wiki_info_wiki_id'] = $objWikiInfoWikiIdArr;
                if ($objWikiInfoWikiIdArr) {
                    $res['obj_is_related_wiki'] = in_array($wikiDataMap[$value['basic_id']],
                        $objWikiInfoWikiIdArr);
                } else {
                    $res['obj_is_related_wiki'] = false;
                }
                $obj_type = IdParse::getType($value['obj_id']);
                if ((int)$obj_type === BlockType::TYPE_PHOTO) {
                    $res['type'] = $noteData[$value['obj_id']]['type'] ?? ''; //type 0 表示图片
                    $res['title'] = $noteData[$value['obj_id']]['photo']['photo_info']['title'] ?? ''; //标题
                    $res['remark'] = $noteData[$value['obj_id']]['photo']['photo_info']['remark'] ?? '';//内容
                    $res['nickName'] = $noteData[$value['obj_id']]['photo']['user_info']['nick'] ?? '';//发布者
                    $res['image'] = $noteData[$value['obj_id']]['photo']['photo_info']['image_list'][0]['ori_pic_url'] ?? ''; //图片
                    $res['noteAddtime'] = date('Y-m-d',
                            $noteData[$value['obj_id']]['photo']['photo_info']['addtime']) ?? '';//note发布日期
                }
                if ((int)$obj_type === BlockType::TYPE_BLANK) {
                    $res['type'] = $blankData[$value['obj_id']]['type'] ?? ''; //type 0 表示图片
                    $res['title'] = $blankData[$value['obj_id']]['blank']['blank_info']['title'] ?? ''; //标题
                    $res['remark'] = $blankData[$value['obj_id']]['blank']['blank_info']['remark'] ?? '';//内容
                    $res['nickName'] = $blankData[$value['obj_id']]['blank']['user_info']['nick'] ?? '';//发布者
                    $res['image'] = $blankData[$value['obj_id']]['blank']['blank_info']['cover_pic_url'] ?? '';//图片
                    $res['noteAddtime'] = date('Y-m-d',
                            $blankData[$value['obj_id']]['blank']['blank_info']['addtime']) ?? '';//note发布日期

                }

                $result[] = $res;
            }
        }

        return $result;

    }

    /**
     * 根据obj_id/获取该obj关联的wiki商品数据
     * @param $noteIds
     * @param int $wiki_id
     * @return array
     */
    public static function getRelatedWikiByNoteIds($noteIds, $wiki_id = 0): array
    {
        if ($noteIds) {
            $where = [
                'obj_id' => $noteIds,
                'obj_type' => [mObjRelateWiki::OBJ_TYPE_NOTE, mObjRelateWiki::OBJ_TYPE_BLANK],
                'status' => mObjRelateWiki::STATUS_NORMAL,

            ];

            if ($wiki_id) {
                $where['wiki_id'] = $wiki_id;
            } else {
                $where['wiki_id[>]'] = 0;
            }
            $obj_wiki_info = mObjRelateWiki::getByWhere($where, ['wiki_id', 'obj_id']);
            $objWikiInfo = [];
            if ($obj_wiki_info) {
                $wiki_ids = array_column($obj_wiki_info, 'wiki_id');
                $wiki_ids = array_unique($wiki_ids);
                $wiki_info = Wiki::getWikiBaseInfos($wiki_ids);
                if ($wiki_info) {
                    foreach ($obj_wiki_info as $item) {
                        $objWikiInfo[$item['obj_id']][] = $wiki_info[$item['wiki_id']] ?? [];
                        $objWikiInfo['obj_ids'][] = $item['obj_id'];
                    }
                }
            }

            return $objWikiInfo;
        } else {
            return [];
        }

    }

    /**
     * @param $noteId
     * @return false|string
     */
    public static function creatLinkUrl($noteId)
    {
        $linkParams = ['note_id' => $noteId, 'pin_id' => ''];
        $urlArr = LinkFormat::generateLink(LinkConf::LINK_NOTE, json_encode($linkParams));
        $urlArr = [
            'type' => 'link',
            'link' => $urlArr['app_template'],
        ];

        return json_encode($urlArr);
    }

    /**
     * 获取已公布名单
     * @param $fineGoodsId
     * @return array|bool
     */
    public static function getJoined($fineGoodsId)
    {
        $where['fine_goods_id'] = $fineGoodsId;
        $where['join_status'] = FineGoodsJoinModel::JOIN_STATUS_PREFER;

        return FineGoodsJoinModel::select('*', $where) ?? [];

    }

    /**
     * @param array $data
     * @return array
     */
    public static function formatJoined(array $data): array
    {
        $ids = array_column($data, 'record_id');
        $fansNumMap = FineGoodsJoinRecordModel::select(['fans_num', 'uid'], ['id' => $ids]);
        $result = [];
        if ($fansNumMap && is_array($fansNumMap)) {
            $uidArr = array_column($data, 'uid');
            $fansNumMap = NewProductWinnerListService::handleData($fansNumMap, 'uid', 'fans_num');
            $user_infos = mUser::getBrandCards($uidArr, 0);

            //快递信息
            $couriersMap = NewProductWinnerListService::handleData(mShopCourier::getByCourierIds(array_unique(array_column($data,
                'courier_id'))), 'courier_id');
            //用户综合评分
            list($scoreMap, $tag) = BigDataService::getScoreMap($uidArr);


            foreach ($data as $val) {
                $res = [];
                $res['fans_num'] = $fansNumMap[$val['uid']] ?? 0;
                $userInfo = $user_infos[$val['uid']] ?? [];
                $res['user_avatar'] = $userInfo['avatar'] ?? '';
                $res['user_nick'] = $userInfo['nick'] ?? '';
                $res['user_score'] = $scoreMap[$val['uid']] ?? [];
                $res['id'] = $val['id'];
                $res['logistics_status'] = $val['logistics_status'];
                $res['user_uid'] = $val['uid'];
                $res['record_id'] = $val['record_id']; //关联fine_goods_test_activity_join_record主键id
                $res['tag_list'] = $tag[$val['uid']]['tag'] ?? ''; //用户标签
                $res['tracking_number'] = $val['tracking_number'] ?? '';//物流单号
                $res['logistics_status'] = $val['logistics_status'] ?? '';//发货状态
                $couriersInfo = $couriersMap[$val['courier_id']] ?? []; //物流公司详细信息
                if ($couriersInfo) {
                    $res['couriers_info_courier_name'] = $couriersInfo['courier_name'] ?? ''; //物流公司名称
                }
                $result [] = $res;
            }
        }

        return $result;

    }

    /**
     *
     * 获取note列表-（活动id获取）
     * @param $fine_goods_ids
     * @param int $uid
     * @return array
     */
    public static function getNoteListById($fine_goods_ids, int $uid = 0): array
    {
        $note_ids = [];
        $blank_ids = [];
        $list = [];
        //获取全部内容obj_id
        $where = [
            'fine_goods_id' => $fine_goods_ids,
            'ORDER' => ["points" => "DESC", 'addtime' => "DESC"],
            'is_delete[!]' => FineGoodsContentModel::IS_DELETE_TRUE,
        ];
        $reports = FineGoodsContentModel::all($where, ['obj_id', 'fine_goods_id']);
        if (!$reports) {
            return $list;
        }
        $obj_ids = array_column($reports, 'obj_id');
        $report_list = self::getNoteListByObjIds($obj_ids, $uid);
        if (!$report_list) {
            return $list;
        }
        //获取内容
        foreach ($reports as $report) {
            if (isset($report_list[$report['obj_id']]) && $report_list[$report['obj_id']]) {
                $list[$report['fine_goods_id']][] = $report_list[$report['obj_id']];
            }
        }

        return $list;
    }

    /**
     * 获取note列表-（活动$obj_ids获取）
     * @param $obj_ids
     * @param int $uid
     * @return array
     */
    public static function getNoteListByObjIds($obj_ids, int $uid = 0): array
    {
        $note_ids = [];
        $blank_ids = [];
        //obj_id 分类
        foreach ($obj_ids as $obj_id) {
            $obj_type = IdParse::getType($obj_id);
            if ((int)$obj_type === BlockType::TYPE_PHOTO) {
                $note_ids[] = $obj_id;
            }
            if ((int)$obj_type === BlockType::TYPE_BLANK) {
                $blank_ids[] = $obj_id;
            }
        }
        $note_lists = $note_ids ? HandleNote::handleNote($note_ids, FormatScene::BASE_INFO, $uid) : [];
        $blank_lists = $blank_ids ? HandleBlank::handleBlank($blank_ids, FormatScene::BASE_INFO, $uid) : [];

        return array_merge($note_lists, $blank_lists);
    }

    /**
     * 获取 关联wiki的内容列表
     * @param $obj_ids
     * @param int $wiki_type
     * @param int $wiki_id
     * @return array
     */
    public static function getObjInfo($obj_ids, int $wiki_type = 3, int $wiki_id = 0): array
    {
        $note_ids = [];
        $blank_ids = [];
        //获取关联wiki
        $info = self::getRelatedWikiByNoteIds($obj_ids, $wiki_id);
        //obj_id 分类
        foreach ($obj_ids as $obj_id) {
            $obj_type = IdParse::getType($obj_id);
            if ((int)$obj_type === BlockType::TYPE_PHOTO) {
                $note_ids[] = $obj_id;
            }
            if ((int)$obj_type === BlockType::TYPE_BLANK) {
                $blank_ids[] = $obj_id;
            }
        }
        $note_lists = Photos::getPhotoInfoTime($note_ids, ['id(obj_id)', 'title', 'remark', 'pic_id(cover_pic_id)', 'addtime', 'uid']) ?: [];
        $blank_lists = Blank::getBlankRemarkByIds($blank_ids,
            ['bid(obj_id)', 'title', 'remark', 'cover_pic_id', 'addtime', 'uid']) ?: [];
        $list = array_merge($note_lists, $blank_lists);
        if (!$list) {
            return [];
        }
        $isset_obj_ids = $info['obj_ids'] ?? [];
        $isset_obj_ids = array_unique($isset_obj_ids);
        //有wiki
        $new_list = [];
        if (($wiki_type === 1) && $info) {
            foreach ($list as $k => $item) {
                if (in_array($item['obj_id'], $isset_obj_ids, false)) {
                    $new_list[$k] = self::_getNewList($info, $item);
                }
            }
        }

        //无wiki
        if ($wiki_type === 2) {
            foreach ($list as $k => $item) {
                if (!in_array($item['obj_id'], $isset_obj_ids, false)) {
                    $new_list[$k] = self::_getNewList($info, $item);
                }
            }
        }
        if ($wiki_type === 3) {
            foreach ($list as $k => $item) {
                $new_list[$k] = self::_getNewList($info, $item);
            }

        }

        return $new_list;

    }

    /**
     * 获取新的列表
     * @param $info
     * @param $item
     * @return array
     */
    private static function _getNewList($info, $item)
    {
        $new_list['obj_type'] = IdParse::getType($item['obj_id']);
        $new_list['cover_image'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $item['cover_pic_id'],
            ImgUrl::IMAGE_SIZE_ORI_NPHONE);
        $new_list['add_time'] = date("Y-m-d H:i:s", $item['addtime']);
        $new_list['wiki_list'] = $info[$item['obj_id']] ?? [];
        $new_list['id'] = random_int(0, 100000);
        $new_list['title'] = $item['title'] ?? '';
        $new_list['remark'] = $item['remark'] ?? '';
        $new_list['cover_pic_id'] = $item['cover_pic_id'] ?? '';
        $new_list['addtime'] = $item['addtime'] ?? 0;
        $new_list['uid'] = $item['uid'] ?? 0;
        $new_list['obj_id'] = $item['obj_id'];
        $new_list['link'] = self::creatLinkUrl($item['obj_id']); //扫码url

        return $new_list;
    }

    /**
     * 获取首选人的发货信息
     * @param $id
     * @return array
     * @throws \Exception
     */
    public static function getShipInfo($id): array
    {
        $info = FineGoodsJoinModel::get(['uid', 'fine_goods_id', 'record_id'], ['id' => $id]);
        if (!$info) {
            throw new Exception('数据不存在');
        }
        $detail = FineGoodsJoinRecordModel::get(['name', 'encrypt_phone_id', 'address'], ['id' => $info['record_id']]);
        $userInfo = mUser::getUser($info['uid']);
        $detail['nick_name'] = $userInfo['nick'] ?? '';
        $basic_title = self::getById($info['fine_goods_id'], ['basic_title'])['basic_title'] ?? '';
        $detail['prize_name'] = $basic_title;
        $detail['uid'] = $info['uid'];
        $detail['couriers'] = NewProductWinnerListService::getCourierList();
        $detail['phone'] = PhoneModel::getExtendPhone($detail['encrypt_phone_id'], UserExtendPhoneScene::GOODS_TEST_JOIN_PHONE);

        return $detail ?? [];
    }


    /**
     * 获取许愿词列表
     * @param string $brand_name
     * @param string $field
     * @param array $where
     * @return array|bool
     */
    public static function getWishMsg(string $brand_name, $field = "*", array $where = [])
    {
        $where['wish_status'] = FineGoodsWishMsgModel::STATUS_NORMAL;
        $list = FineGoodsWishMsgModel::all($where, $field);
        foreach ($list as &$item) {
            $item['content'] = str_replace("{品牌名}", $brand_name, $item['content']);
            $item['emoji_url'] = $item['emoji_url'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $item['emoji_url'],
                ImgUrl::IMAGE_SIZE_ORI_NPHONE) : '';
        }

        return $list;
    }

    /**
     * 添加消息记录(批量)
     * @param $msg_type
     * @param array $params 二维数组
     * @return bool|\PDOStatement
     */
    public static function addMsgRecord($msg_type, array $params)
    {
        $data = [];
        foreach ($params as $k => $param) {
            $data[$k]['uid'] = $param['uid'];
            $data[$k]['msg_type'] = $msg_type;
            $data[$k]['fine_goods_id'] = $param['fine_goods_id'];
//            $data[$k]['content'] = $param['content'];
            $data[$k]['wish_id'] = $param['wish_id'] ?? 0;
        }
        sort($data);

        return FineGoodsMsgModel::insert($data);
    }

    /**
     * 获取选中状态的内容
     * @param $fine_goods_id
     * @param $field
     * @return array
     */
    public static function getSelectedContent($fine_goods_id, $field = "*"): array
    {
        $where['fine_goods_id'] = $fine_goods_id;
        $where['is_delete'] = FineGoodsContentModel::IS_DELETE_FALSE;

        return FineGoodsContentModel::all($where, $field);

    }

    public static function getActivityUrl($activityId)
    {
        $link = Hhzurl::getDomain() . '/brand/light-test/detail?id=' . $activityId;

        return LinkFormat::encryptionLink($link);
    }

    /**
     * 获取符合字段和字段值的数组集合
     * @param array $data 待过滤数组
     * @param string $field 要查找的字段
     * @param $value //要查找的字段值
     * @return array 返回所有符合要求的数组集合
     */
    public static function arrayFilterFieldValue(array $data, string $field, $value): array
    {
        return array_filter($data, function ($row) use ($field, $value) {
            if (isset($row[$field])) {
                return $row[$field] == $value;
            }
        });
    }


    /**
     * 批量获取 活动申请人数
     * @param $fineGoodsIds
     * @return array
     */
    public static function getApplyCount($fineGoodsIds): array
    {
        $where = [
            'fine_goods_id' => $fineGoodsIds,
            "GROUP" => "fine_goods_id",
        ];
        return NewProductWinnerListService::handleCount(FineGoodsJoinRecordModel::getCountMaps($where), 'fine_goods_id');

    }

    /**
     * 商业合作中心使用
     * @param $isApply 只查进行中的：1 ,全部：0
     * @param $page
     * @param $pageSize
     * @return array
     * @throws \JsonException
     */
    public static function getListForMCN($isApply = 0, $page = 1, $pageSize = 10)
    {
        $isOver = 1;
        $result = [];
        $applyList = [];
        $endList = [];
        $now = time();
        if ($page == 1 || $isApply) {
            $applyList = FineGoodsModel::selectList([
                'type[!]' => FineGoodsModel::TYPE_EVALUATION_OLD,
                'schedule_start_time[<=]' => $now,
                'schedule_end_time[>]' => $now,
                'activity_state' => FineGoodsModel::STATE_PASS,
                'ORDER' => ['schedule_end_time' => 'ASC']
            ]);
        }
        if ($isApply == 0) {
            $where = [
                'type[!]' => FineGoodsModel::TYPE_EVALUATION_OLD,
                'schedule_start_time[>]' => 0,
                'schedule_end_time[>]' => 0,
                'schedule_end_time[<]' => $now,
                'activity_state' => FineGoodsModel::STATE_PASS,
                'LIMIT' => [($page - 1) * $pageSize, $pageSize],
                'ORDER' => ['schedule_end_time' => 'ASC']
            ];
            $endList = FineGoodsModel::selectList($where);
            unset($where['ORDER']);
            unset($where['LIMIT']);
            $count = FineGoodsModel::selectCount($where);
            $isOver = ($page * $pageSize >= $count) ? 1 : 0;
        }
        $list = array_merge($applyList, $endList);
        foreach ($list as $row) {
            $status = mGoodsRecommender::STATUS_ALL_END;//已结束
            if ($row['schedule_start_time'] <= $now && $row['schedule_end_time'] > $now) {
                $status = mGoodsRecommender::STATUS_START;
            }
            $link = BrandActivity::getFindGoodsTestLink($row['id']);
            $link = LinkFormat::encryptionLink($link);
            $result[] = [
                'id' => $row['id'],
                'title' => $row['brand_name'] ? ($row['brand_name'] . ' | ' . $row['activity_title']) : $row['activity_title'],
                'type' => $row['type'],
                'type_name' => '好好测' . ' | ' . FineGoodsModel::TYPE_MAP[$row['type']],
                'pic_url' => $row['cover_img_url'],
                'start_time' => date('m-d', $row['schedule_start_time']),
                'end_time' => date('m-d', $row['schedule_end_time']),
                'activity_url' => $link,
                'status' => $status,//3:进行中 6:已结束,
            ];
        }
        return ['list' => $result, 'is_over' => $isOver];
    }
}